package com.polaris.live.popup

import android.content.Context
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ConvertUtils
import com.lxj.xpopup.core.BottomPopupView
import com.polaris.live.adapter.CountryAdapter
import com.polaris.live.common.AppModule
import com.polaris.live.common.R
import com.polaris.live.common.databinding.PopupCountryBinding
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.network.state.ResultState
import com.polaris.live.common.recyclerview.CommonItemDecoration
import com.polaris.live.resp.back_resp.AreaCodeResp
import com.polaris.live.viewmodel.InfoUserViewModel
import java.util.Collections

/**
 * 国家弹窗
 *
 * @author Created by 长空 on 2023/10/25/004 17:21
 */
class CountryPopup(
    context: Context,
    private val mViewModel: InfoUserViewModel,
    private val mAreaCode: String,
    private val mOnCountryCallBack: ((countryCode: String, isHidden: Boolean) -> Unit),
) : BottomPopupView(context) {

    private lateinit var mBinding: PopupCountryBinding
    private val mAdapter by lazy { CountryAdapter() }

    private val mAreaCodeList = mutableListOf<AreaCodeResp>()
    private var mSelectIndex = -1

    override fun getImplLayoutId(): Int {
        return R.layout.popup_country
    }

    override fun onCreate() {
        super.onCreate()

        mBinding = PopupCountryBinding.bind(popupImplView)

        mAreaCodeList.add(AreaCodeResp())
        mAreaCodeList.add(AreaCodeResp())

        mBinding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
            addItemDecoration(CommonItemDecoration(bottomMargin = ConvertUtils.dp2px(130f)))
            adapter = mAdapter
        }

        initListener()
        initObserver()

        initData()
    }

    private fun initObserver() {
        mViewModel.mIpLiveData.observe(this) { state ->
            when (state) {
                is ResultState.Success -> {
                    val countryCode = state.data.country ?: AppModule.getLanguageCountry()
                    val country = mAreaCodeList.find { it.countryCode == countryCode }
                    val index = mAreaCodeList.indexOf(country)
                    if (index != -1) {//如果找到了默认国家则替换位置
                        Collections.swap(mAreaCodeList, index, 1)
                        Collections.swap(mAdapter.data, index, 1)
                        mAreaCodeList.removeAt(index)
                        mAdapter.data.removeAt(index)
                        mAdapter.notifyDataSetChanged()
                    } else {//没找到则移除
                        mAreaCodeList.removeAt(1)
                        mAdapter.removeAt(1)
                        mAdapter.setDefault(false)
                    }
                    showDefaultSelect()
                }

                else -> {
                    showDefaultSelect()
                }
            }
        }
        mViewModel.mAllAreaCodeLiveData.observe(this) { areaCodes ->
            areaCodes.forEach {
                it.firstLetter = it.countryName?.get(0)?.toString()
            }

            mAreaCodeList.addAll(areaCodes.filter { it.countryName != null })
            mAreaCodeList.sortBy { it.countryName?.first()?.uppercaseChar() }

            mViewModel.getIp()

            showDefaultSelect()
        }
    }

    private fun showDefaultSelect() {
        val countrySelect = mAreaCodeList.find { it.countryCode == mAreaCode }
        val indexSelect = mAreaCodeList.indexOf(countrySelect)
        mSelectIndex = if (indexSelect != -1) {
            mAdapter.setSelectDefault(indexSelect)
            indexSelect
        } else {
            mAdapter.setSelectDefault(0)
            0
        }
        mAdapter.setList(mAreaCodeList)
    }

    private fun initListener() {
        mAdapter.setOnItemClickListener { _, _, position ->
            mAdapter.clearSelected()

            mAdapter.setSelect(position)
            mSelectIndex = position
        }

        mBinding.spSave.setOnSingleClickListener {
            if (mSelectIndex == -1) { //没有加载到数据直接退出
                dismiss()
                return@setOnSingleClickListener
            }
            val countryCode = if (mSelectIndex == 0) {
                ""
            } else {
                if (mSelectIndex > 0 && mSelectIndex < mAdapter.data.size && mAdapter.data.size > 0) {
                    mAdapter.data[mSelectIndex].countryCode.toString()
                } else {
                    ""
                }
            }
            mOnCountryCallBack.invoke(countryCode, mSelectIndex == 0)
            dismiss()
        }
    }

    private fun initData() {
        mViewModel.getAllAreaCode()
    }
}